package com.xbjtech.service;

import java.util.List;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xbjtech.mapper.RoleMapper;
import com.xbjtech.model.Role;

@Service
public class RoleService extends BaseService<Role> {
	
	@Autowired
	RoleMapper roleMapper;
	
	/**
	 * 批处理
	 * 1. 基本不用这种写法：insert into table values(1,2),(1,3),(1,4)
	 * 2. 迭代  for insert  开发方便  
	 * 3. BatchExecutor  性能好   数据量大于30以上
	 */
	
	@Autowired
	SqlSessionFactory sqlSessionFactory;
	
	public void insertRoleAndRes(Integer rid, List<Integer> resIds) {
		SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
		try {
			RoleMapper roleMapper = session.getMapper(RoleMapper.class);
			roleMapper.deleteResByRid(rid);
			for (Integer resId : resIds) {
				roleMapper.insertRoleAndRes(rid, resId);
			}
			session.commit();
			session.clearCache();
		} catch (RuntimeException e) {
			e.printStackTrace();
			session.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	
	public List<Integer> selectResByRid(Integer rid) {
		return roleMapper.selectResByRid(rid);
	}

}
